package main

/**
Write a program to find the node at which the intersection of two singly linked lists begins.


For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗
B:     b1 → b2 → b3
begin to intersect at node c1.


Notes:

If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
*/

/**
C实现
思路:
	有两个链表A，B，两者可能从某个结点起开始重合，求该点位置
	如果A,B从某个结点其开始重合，那么势必从该点起他们后续长度是相同的，
	我们先让AB长度保持一致，然后一一对比
struct ListNode {
    int val;
    struct ListNode *next;
};

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB);

int main() {

    struct ListNode d = {12, NULL};
    struct ListNode e = {13, NULL};


    struct ListNode a = {11, &d};
    struct ListNode b = {11, &e};


    struct ListNode *c = getIntersectionNode(&a, &b);
    if (c == NULL) {
        printf("intersection node is null");
    } else {
        printf("intersection node val is %d", c->val);
    }
    return 0;
}

int len(struct ListNode *headA) {
    int l = 0;
    while (headA != NULL) {
        l++;
        headA = headA->next;
    }

    return l;
}

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {

    if (headA == NULL || headB == NULL) {
        return NULL;
    }

    if (len(headA) > len(headB)) {
        while (len(headA) != len(headB)) {
            headA = headA->next;
        }
    } else {
        while (len(headA) != len(headB)) {
            headB = headB->next;
        }
    }

    while (headA != headB) {
        headA = headA->next;
        headB = headB->next;
    }

    return headA;
}

*/
